package com.nf.action;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.nf.entity.QueryStudent;
import com.nf.entity.Student;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;

@WebServlet("/test")
public class Test extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //配置一下UTF-8编码
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        String height = request.getParameter("height");
        int clinetHeight = 0;
        try {
            clinetHeight = Integer.parseInt(height);
        }catch (Exception e){
            System.out.println("转换失败："+e.getMessage());
            clinetHeight = 180;
        }



        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            String url = "jdbc:mysql://localhost:3306/students?useUnicode=ture&characterEncoding=UTF-8";
            String userName = "root";
            String password = "123456";

            Connection conn = DriverManager.getConnection(url,userName,password);
            System.out.println( conn );

            CallableStatement csmt = conn.prepareCall("{ call xxx6( ?,?,?,?) }");
            csmt.setInt(1,clinetHeight);
            ResultSet rs = csmt.executeQuery();
            //模拟从数据中，已经取出数据
            QueryStudent stuList = new QueryStudent();
            while (rs.next()){
                Student s1 = new Student();
                s1.setId( rs.getInt("id")  );
                s1.setUsername( rs.getString("user_name") );
                s1.setSex( rs.getString("sex") );
                s1.setHeight( rs.getInt("height") );
                stuList.getStudentList().add(s1);
            }

            stuList.setMycount( csmt.getInt(2) );
            stuList.setMycountboy( csmt.getInt(3));
            stuList.setMycountgirl( csmt.getInt(4) );

            //把java对象变成json字符串
            ObjectMapper objectMapper = new ObjectMapper();
            String json = objectMapper.writeValueAsString(stuList);

            //输出字符串
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            PrintWriter out = response.getWriter();
            out.print( json );
        } catch (ClassNotFoundException e) {
            System.out.println("加载驱动时发生异常："+e.getMessage());
        }catch (SQLException e){
            System.out.println("和数据库通讯时发生异常："+e.getMessage());
        }








    }
}
